from flask import Blueprint, render_template, request, jsonify
from model import HouseInfo
from sqlalchemy import func

index_page = Blueprint('index_page', __name__)


@index_page.route('/')
def index():
    # 获取最新房源top6
    house_new_list = HouseInfo.query.order_by(HouseInfo.publish_time.desc()).limit(6).all()
    print(house_new_list)

    # 获取最热房源top4
    house_hot_list = HouseInfo.query.order_by(HouseInfo.page_views.desc()).limit(4).all()
    print(house_hot_list)

    all_housenum = HouseInfo.query.count()
    print(all_housenum)
    return render_template('index.html',
                           house_new_list=house_new_list,
                           house_hot_list=house_hot_list,
                           all_housenum=all_housenum)


@index_page.route('/search/keyworld/', methods=['POST'])
def search_kw():
    kw = request.form.get('kw')
    info = request.form.get('info')
    if info == '地区搜索':
        house_data = HouseInfo.query.with_entities(
            HouseInfo.address, func.count()).filter(HouseInfo.address.contains(kw))
        result = house_data.group_by('address').order_by(func.count().desc()).limit(9).all()
        if len(result):
            data = []
            for i in result:
                data.append({'address': i[0], 'num': i[1]})
                return jsonify({'code': 1, 'info': data})
            else:
                return jsonify({'code': 0, 'info': []})
        if info == '户型搜索':
            house_data = HouseInfo.query.with_entities(HouseInfo.house_type, func.count()).filter(HouseInfo.house_type.contains(kw))
            result = house_data.group_by('house_type').order_by(func.count().desc()).limit(9).all()
            if len(result):
                data = []
                for i in result:
                    data.append({'house_type': i[0], 'num': i[1]})
                    return jsonify({'code': 1, 'info': data})
                else:
                    return jsonify({'code': 0, 'info': []})
